//
//  SureIndentViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/15.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "SureIndentViewController.h"
#import "PayTypeViewController.h"
#import "ChoseAddressViewController.h"
#import "AddAddressViewController.h"
@interface SureIndentViewController ()<UITextViewDelegate>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIView *addressView;
@property (strong, nonatomic) IBOutlet UIView *detailView;
@property (strong, nonatomic) IBOutlet UIButton *addAddressButton;

@property (weak, nonatomic) IBOutlet UILabel *textViewBack;
@property (strong, nonatomic) IBOutlet UITextView *textView;

@property (strong, nonatomic) IBOutlet UIButton *payButton;
@property (weak, nonatomic) IBOutlet UILabel *lowPriceLabel;
@property (strong, nonatomic) IBOutlet UILabel *sumMoney;
@property (weak, nonatomic) IBOutlet UILabel *productNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *productPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *sizeLabel;
@property (weak, nonatomic) IBOutlet UILabel *smallCountPrice;
@property (weak, nonatomic) IBOutlet UIImageView *productImage;
@property (weak, nonatomic) IBOutlet UILabel *userAdressPhone;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (weak, nonatomic) IBOutlet UILabel *userDetailAdress;

@property (strong, nonatomic) NSDictionary *adressDic;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;



@end

@implementation SureIndentViewController


- (void)viewWillAppear:(BOOL)animated{
    if (_addressView.hidden == YES) {
        _detailView.frame =flexibleFrame(CGRectMake(0, 110, 320,304), NO);
    }else{
     _detailView.frame =flexibleFrame(CGRectMake(0, 150, 320, 304), NO);
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hadPay) name:@"hadPay" object:@"1"];
    _adressDic = [NSDictionary dictionary];
    [self initViewlayout];
    [self queryDefaultMallShippingAddress];
    
}



- (void)initViewlayout{
     self.view.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.addressView];
    [self adaptiveViewLayout:self.detailView];
    _scroView.contentSize = flexibleSize(CGSizeMake(320, 455), NO);
    
    _payButton.layer.cornerRadius = 16*VerticalRatio();
    
    _addAddressButton.layer.cornerRadius = 15*VerticalRatio();
    
   
    
    _textViewBack.layer.cornerRadius = 26.5*VerticalRatio();
    _textViewBack.layer.borderWidth = 1;
    _textViewBack.layer.borderColor = [UIColor colorWithWhite:0.941 alpha:1.000].CGColor;
    
    _textView.delegate = self;
    
    //加载商品数据
    self.productNameLabel.text = [NSString stringWithFormat:@"%@",_productDic[@"mgooName"]];
    
    self.sizeLabel.text = [NSString stringWithFormat:@"面积：%@m²",_countSize];

    
     NSString *productPrice = [NSString stringWithFormat:@"价格：￥%@/m²",_productDic[@"mgooPrice"]];;
    NSMutableAttributedString *stri = [[NSMutableAttributedString alloc] initWithString:productPrice];
    [stri addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(3,productPrice.length-3)];
    _productPriceLabel.attributedText = stri;
    
    
    NSString *smallPrice = [NSString stringWithFormat:@"小计：￥%.2f",[_productDic[@"mgooPrice"]floatValue]*[_countSize floatValue]];
    NSMutableAttributedString *strin = [[NSMutableAttributedString alloc] initWithString:smallPrice];
    [strin addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(3,smallPrice.length-3)];
    _smallCountPrice.attributedText = strin;
   
    
    CGFloat totalPri = [_productDic[@"mgooPrice"]floatValue]*[_countSize floatValue];
    if (_totalPrice&&_totalPrice>totalPri) {
        totalPri = _totalPrice;
        _lowPriceLabel.hidden = NO;
        _lowPriceLabel.text = [NSString stringWithFormat:@"最低消费:%.2f元",_totalPrice];
    }
    NSString *totalPrice = [NSString stringWithFormat:@"总金额: ￥%.2f",totalPri];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:totalPrice];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4,totalPrice.length-4)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(4,totalPrice.length-4)];
    _sumMoney.attributedText = str;
}
#pragma mark == 查询默认收货地址
- (void)queryDefaultMallShippingAddress{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryDefaultMallShippingAddress withHttpType:@"POST" withTag:HK_HK_queryDefaultMallShippingAddress];
    
}
- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark   ===修改地址
- (IBAction)changeAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
    AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    page.addressInfo = [_adressDic mutableCopy];
    page.endEditBlock = ^(NSString * delected){
        if ([delected isEqualToString:@"0"]) {
            [self getAddressInfo];
        }else{
            _addressView.hidden = YES;
        }
        
    };
    [[Common getNavigation]pushViewController:page];
    
}

#pragma mark  === 修改完地址后查询地址详情
- (void)getAddressInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%@",_adressDic[@"msadId"]] forKey:@"msadId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMallShippingAddressById withHttpType:@"POST" withTag:HK_HK_queryMallShippingAddressById];
}

#pragma mark   ====选择地址
- (IBAction)choseAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
    ChoseAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ChoseAddress"];
    page.choseAddress = ^(NSDictionary * dic){
        _adressDic = dic;
        _addressView.hidden = NO;
        _userName.text = dic[@"msadReceiverName"];
        _userAdressPhone.text = dic[@"msadMobileNo"];
        _userDetailAdress.numberOfLines = 0;
        _userDetailAdress.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
        [_userDetailAdress sizeToFit];
    };
    [[Common getNavigation]pushViewController:page];
    
}


#pragma mark == 立即预约
- (IBAction)payhandel:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    if (!_adressDic) {
        [CWHUDTips showLoadingTips:@"请添加收货地址信息"];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_productDic[@"mgooId"] forKey:@"mgooId"];
    [dic setObject:_countSize forKey:@"modeNum"];
    [dic setObject:@"2" forKey:@"mordSource"];
    [dic setObject:_adressDic[@"msadAreaId"] forKey:@"msadAreaId"];
    [dic setObject:[NSString stringWithFormat:@"%@:00",_dateTime] forKey:@"mordAppointTime"];
    [dic setObject:_textView.text forKey:@"mordRemark"];
    [dic setObject:_adressDic[@"msadId"] forKey:@"mordAddressId"];
   
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_saveMallOrder withHttpType:@"POST" withTag:HK_HK_saveMallOrder];
    
}

//支付完成通知执行方法
- (void)hadPay{
    [self backBtn];
}

#pragma mark == 跳转地址列表
- (IBAction)gotoAdressListPage:(UIButton *)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
    ChoseAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ChoseAddress"];
    page.choseAddress = ^(NSDictionary * dic){
        _detailView.frame =CGRectMake(0, 150, 320, _detailView.frame.size.height);
        _adressDic = dic;
        _addressView.hidden = NO;
        _addAddressButton.hidden = YES;
        _userName.text = dic[@"msadReceiverName"];
        _userAdressPhone.text = dic[@"msadMobileNo"];
        _userDetailAdress.frame = flexibleFrame(CGRectMake(90, 89, 206, 0), NO);
        _userDetailAdress.numberOfLines = 0;
        _userDetailAdress.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
        [_userDetailAdress sizeToFit];
    };
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - <UITextViewDelegate>
- (void)textViewDidChange:(UITextView *)textView{
    
    if (self.textView.text.length > 0) {
        self.placeHolder.hidden = YES;
    }else{
        self.placeHolder.hidden = NO;
    }
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==HK_HK_queryDefaultMallShippingAddress || tag == HK_HK_queryMallShippingAddressById) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"];
            _adressDic = dic;
            if (![dic isEqual:[NSNull null]]) {
                _addressView.hidden = NO;
                 _detailView.frame =flexibleFrame(CGRectMake(0, 150, 320, 304), NO);
                _userName.text = dic[@"msadReceiverName"];
                _userAdressPhone.text = dic[@"msadMobileNo"];
                _userDetailAdress.numberOfLines = 0;
                _userDetailAdress.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
                [_userDetailAdress sizeToFit];
            }else{
                _addressView.hidden = YES;
            }
            
        }
    }else if (tag == HK_HK_saveMallOrder){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
            PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
            page.payOrderPrice = database[@"result"][@"mordPrice"];
            page.payOrderName = _productDic[@"mgooName"];
            page.payId = database[@"result"][@"mordNo"];
//            page.paySuccessBlock = ^(){
//                [self backBtn];
//            };
            [[Common getNavigation]pushViewController:page completion:^{
                 [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            }];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hadPay" object:@"1"];
}

@end
